package com.centling.tools;

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.params.DefaultHttpParams;
import org.apache.commons.httpclient.protocol.Protocol;

/**
 * REST API工具类
 * 
 * @author cyril
 * @date 2017年5月4日
 * @version V1.0
 */
public class RestUtils {

	/**
	 * 发送GET请求
	 * 
	 * @param url
	 * @return
	 */
	public static String sendGet(String url) {
		// 忽略SSL
		ignoreSSL();
		HttpClient client = new HttpClient();
		GetMethod get = new GetMethod(url);
		get.releaseConnection();
		get.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
		get.setRequestHeader("Accept", "application/json");
		String result = "";
		try {
			client.executeMethod(get);
			result = new String(get.getResponseBodyAsString().getBytes("gbk"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 发送POST请求
	 * 
	 * @param url
	 */
	public static String sendPost(String url) {
		// 忽略SSL
		ignoreSSL();
		HttpClient client = new HttpClient();
		PostMethod post = new PostMethod(url);
		post.releaseConnection();
		post.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
		post.setRequestHeader("Accept", "application/json");
		String result = "";
		try {
			client.executeMethod(post);
			result = new String(post.getResponseBodyAsString().getBytes("gbk"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 发送PUT请求
	 * 
	 * @param url
	 * @param params
	 */
	@SuppressWarnings("deprecation")
	public static String sendPut(String url, String params) {
		// 忽略SSL
		ignoreSSL();
		HttpClient client = new HttpClient();
		PutMethod put = new PutMethod(url);
		put.releaseConnection();
		put.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
		put.setRequestHeader("Accept", "application/json");
		put.setRequestBody(params);
		String result = "";
		try {
			client.executeMethod(put);
			result = new String(put.getResponseBodyAsString().getBytes("gbk"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 忽略SSL
	 */
	public static void ignoreSSL() {
		Protocol myhttps = new Protocol("https", new MySSLProtocolSocketFactory(), 443);
		Protocol.registerProtocol("https", myhttps);
		// 设置策略，防止报cookie错误
		DefaultHttpParams.getDefaultParams().setParameter("http.protocol.cookie-policy",
				CookiePolicy.BROWSER_COMPATIBILITY);
	}

}
